package info.cs52.fes.action;

import info.cs52.fes.FesAction;
import info.cs52.fes.dao.DishDAO;
import info.cs52.fes.data.Dish;
import info.cs52.fes.data.Meal;
import info.cs52.fes.data.User;
import info.cs52.fes.prolog.Engine;
import info.cs52.fes.prolog.TuPrologEngine;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;

import com.google.appengine.api.datastore.Text;

public class DialogueAction extends FesAction {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doIt(req);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doIt(req);
	}

	private void doIt(HttpServletRequest req) {
		history = req.getParameter("history");
		String question = req.getParameter("question");
		String answer = req.getParameter("answer");
		
		Engine engine = new TuPrologEngine();
		User user = SessionUtils.getUser(req);
		if (user.getKnowledgeBase() != null) {
			engine.setUserKnowledgeBase(user.getKnowledgeBase().getValue());
		}
		if (question != null && answer != null) {
			String term = engine.process(question, answer, 1.0f);
			user.setKnowledgeBase(new Text(
					user.getKnowledgeBase().getValue() + term + "\n"));
			history += "<br/>" + StringEscapeUtils.escapeHtml(answer);
		}
		
		List<List<String>> recommendedMeals = engine.recommend();
		meals = new ArrayList<Meal>();
		for (List<String> recommendedMeal : recommendedMeals) {
			Meal meal = new Meal();
			for (String recommendedDish : recommendedMeal) {
				Dish dish = DishDAO.find(recommendedDish);
				if (dish == null) {
					// TODO generate an error instead
					dish = new Dish(recommendedDish);
				}
				meal.addDish(dish);
			}
			meals.add(meal);
		}
		
		newQuestion = engine.getQuestion();
		if (newQuestion != null) {
			if (history == null) {
				history = newQuestion;
			} else {
				history += "<br/>" + StringEscapeUtils.escapeHtml(newQuestion) + "?";
			}
		}
	}

	private ArrayList<Meal> meals;
	private String history;
	private String newQuestion;

	public ArrayList<Meal> getMeals() {
		return meals;
	}
	
	public String getHistory() {
		return history;
	}
	
	public String getNewQuestion() {
		return newQuestion;
	}
}
